﻿// ItemSelector is a selection manager for a container of items
define([],
function () {
    'use strict';

    var type = 'itemSelector',
    typeManager = Wjs.typeManager,
    dom = Wjs.dom,
    ItemSelector = typeManager.getType(type);

    if (ItemSelector) { // It has been already loaded
        return ItemSelector;
    }

    // Renders the html from a component
    ItemSelector = Wjs.typeBuilder.define({

        type: type,

        selection: [], // The collection of selected items (to allow multiple selection)

        // Whether to allow multiple selection
        multiple: false,

        // Clears the selection
        clear: function () {

            selection.forEach(function (w) {

                if (w.deselect) {
                    w.deselect();
                }
            });

            selection.length = 0;
        },

        // Adds a item to the hash of selection ones
        // If keepPrevious is falsy, the previous selection are removed and the deselect method is called
        select: function (item, keepPrevious) {

            if (!keepPrevious || !this.multiple) {

                this.clear();
            }

            selection.push(item);
        },

        // Removes a selected itemn
        remove: function (item) {
            selection.forEach(function (w, i) {
                if (w === item) {

                    if (w.deselect) {
                        w.deselect();
                    }

                    selection.splice(i, 1);
                }
            });
        }

    });

    typeManager.registerType(ItemSelector);

    return ItemSelector;

});